package edu.ycu.aladdin.collector.service.weibo;

import com.alibaba.dubbo.config.annotation.Service;
import edu.ycu.aladdin.collector.api.CrawlerTaskService;
import edu.ycu.aladdin.collector.api.entity.weibo.UserInfoTaskQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import static edu.ycu.aladdin.collector.RedisPrefix.WEIBO_USER_TASK_INRC;
import static edu.ycu.aladdin.common.constant.MongoConstant.CRAWLER_TASK_WEIBO_USER_INFO;

/**
 * 用户任务队列的mongo实现.
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 2019-04-17 20:35
 */
@Slf4j
@org.springframework.stereotype.Service
@Service(interfaceClass = CrawlerTaskService.class, timeout = 10000, group = "weibo-task-user-info", version = "mongo-v1")
public class WeiBoUserInfoTaskService implements CrawlerTaskService<UserInfoTaskQueue,String,String> {

    private final MongoTemplate mongoTemplate;
    private final RedisTemplate redisTemplate;

    @Autowired
    public WeiBoUserInfoTaskService(MongoTemplate mongoTemplate, RedisTemplate redisTemplate) {
        this.mongoTemplate = mongoTemplate;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public UserInfoTaskQueue requestTask(int size) {
        Long end = redisTemplate.opsForValue().increment(WEIBO_USER_TASK_INRC, size);
        UserInfoTaskQueue taskQueue = new UserInfoTaskQueue(end-size,end);
        mongoTemplate.insert(taskQueue, CRAWLER_TASK_WEIBO_USER_INFO);
        return taskQueue;
    }

    @Override
    public UserInfoTaskQueue delTaskQueue(String s) {
        Query query = new Query(Criteria.where("id").is(s));
        return mongoTemplate.findAndRemove(query, UserInfoTaskQueue.class,CRAWLER_TASK_WEIBO_USER_INFO);
    }

    @Override
    public UserInfoTaskQueue getTaskQueue(String s) {
        Query query = new Query(Criteria.where("id").is(s));
        return mongoTemplate.findOne(query, UserInfoTaskQueue.class,CRAWLER_TASK_WEIBO_USER_INFO);
    }
}
